package com.rockgle.reader;

import java.util.List;

import android.app.Activity;
import android.view.View;

import com.rockgle.persistence.DAO;
import com.rockgle.widget.PostListAdapter;

public class DBContentLoader{

	private DAO dao;
	private SortedEntryList parsedData;
	private PostListAdapter adapter=null;
	private boolean onlyNew;
	
	public DBContentLoader(){
		super();
		this.onlyNew = false;
		dao = new DAO();
	}
	
	public DBContentLoader(boolean onlyNew){
		super();
		this.onlyNew = onlyNew;
		dao = new DAO();
	}
	
	public void execute(PostListAdapter adapter){
		if (!isAllDownloaded()){
			doInBackground(adapter);
			onPostExecute();
		}
	}

	protected Void doInBackground(PostListAdapter adapter) {
		if (adapter!=null){
			this.adapter = adapter;
			SortedEntryList datos = adapter.getData();
			parsedData = datos;

			if (onlyNew){
				if (PreferenceMonitor.getOnlyUnread()){
					getUnreadEntries(0);
				}else{
					getEntries(0);
				}
			}else{
				if (PreferenceMonitor.getOnlyUnread()){
					getUnreadEntries(parsedData.size());
				}else{
					getEntries(parsedData.size());
				}
			}
		}
		return null;
	}
	
	public void getUnreadEntries(int currentfirstentry){
		List<Entry> entries = dao.getUnreadEntries(currentfirstentry);
		if (entries.size()>0){
			for (Entry entry:entries){
				if (!parsedData.contains(entry)){
	            	parsedData.insertSorted(entry);
	            }
			}
		}
	}
	
	public void getEntries(int currentfirstentry){
		List<Entry> entries = dao.getEntries(currentfirstentry);
		if (entries.size()>0){
			for (Entry entry:entries){
				if (!parsedData.contains(entry)){
	            	parsedData.insertSorted(entry);
	            }
			}
		}
	}

	protected void onPostExecute() {
		adapter.notifyDataSetChanged();
		if (adapter!=null){
			Activity act = Main.getInstance();
			if (adapter.isEmpty()){
				act.findViewById(R.id.noEntries).setVisibility(View.VISIBLE);
				act.findViewById(R.id.FeedListView).setVisibility(View.GONE);
			}else{
				act.findViewById(R.id.noEntries).setVisibility(View.GONE);
				act.findViewById(R.id.FeedListView).setVisibility(View.VISIBLE);
			}
		}
	}
	
	public boolean isAllDownloaded(){
		if(parsedData!=null){
			List<Entry> leastRecentEntries = dao.getLeastRecentEntries(1);
			if (leastRecentEntries.size()==0){
				return true;
			}else{
				Entry entry = leastRecentEntries.get(0);
				if (parsedData.contains(entry)){
					return true;
				}else{
					return false;
				}
			}
		}else{
			return false;
		}
	}
}
